import { Request, Response } from 'express';
import { getRepository } from 'typeorm';
import { ListeningRecord } from '../models/ListeningRecord';
import { ListeningMaterial } from '../models/ListeningMaterial';

// 获取用户练习统计
export const getUserListeningStats = async (req: Request, res: Response) => {
  try {
    const recordRepository = getRepository(ListeningRecord);
    const materialRepository = getRepository(ListeningMaterial);

    // 获取用户的所有练习记录
    const records = await recordRepository.find({
      where: { user: { id: req.params.userId } },
      relations: ['material', 'material.category']
    });

    // 计算总体统计
    const totalRecords = records.length;
    const totalDuration = records.reduce((sum, record) => sum + record.duration, 0);
    const averageScore = records.reduce((sum, record) => sum + record.score, 0) / totalRecords;

    // 按分类统计
    const categoryStats = records.reduce((stats, record) => {
      const categoryId = record.material.category.id;
      if (!stats[categoryId]) {
        stats[categoryId] = {
          categoryName: record.material.category.name,
          count: 0,
          totalScore: 0,
          totalDuration: 0
        };
      }
      stats[categoryId].count++;
      stats[categoryId].totalScore += record.score;
      stats[categoryId].totalDuration += record.duration;
      return stats;
    }, {});

    // 计算每个分类的平均分和总时长
    Object.keys(categoryStats).forEach(categoryId => {
      const stats = categoryStats[categoryId];
      stats.averageScore = stats.totalScore / stats.count;
    });

    // 获取最近7天的练习记录
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
    const recentRecords = records.filter(record => record.practiceTime >= sevenDaysAgo);

    // 按日期统计
    const dailyStats = recentRecords.reduce((stats, record) => {
      const date = record.practiceTime.toISOString().split('T')[0];
      if (!stats[date]) {
        stats[date] = {
          count: 0,
          totalScore: 0,
          totalDuration: 0
        };
      }
      stats[date].count++;
      stats[date].totalScore += record.score;
      stats[date].totalDuration += record.duration;
      return stats;
    }, {});

    // 计算错题分析
    const wrongAnswers = records.reduce((wrong, record) => {
      record.answers.forEach(answer => {
        if (!answer.isCorrect) {
          if (!wrong[answer.questionId]) {
            wrong[answer.questionId] = {
              count: 0,
              wrongAnswers: new Set()
            };
          }
          wrong[answer.questionId].count++;
          wrong[answer.questionId].wrongAnswers.add(answer.userAnswer);
        }
      });
      return wrong;
    }, {});

    res.json({
      overall: {
        totalRecords,
        totalDuration,
        averageScore
      },
      categoryStats,
      dailyStats,
      wrongAnswers
    });
  } catch (error) {
    res.status(500).json({ message: '获取练习统计失败', error });
  }
};

// 获取材料难度分析
export const getMaterialDifficultyAnalysis = async (req: Request, res: Response) => {
  try {
    const recordRepository = getRepository(ListeningRecord);
    const materialRepository = getRepository(ListeningMaterial);

    // 获取所有材料
    const materials = await materialRepository.find({
      relations: ['category']
    });

    // 获取每个材料的练习记录
    const materialStats = await Promise.all(materials.map(async material => {
      const records = await recordRepository.find({
        where: { material: { id: material.id } }
      });

      const totalRecords = records.length;
      const averageScore = records.reduce((sum, record) => sum + record.score, 0) / totalRecords || 0;
      const completionRate = records.length / (await recordRepository.count()) * 100;

      return {
        materialId: material.id,
        title: material.title,
        category: material.category.name,
        difficulty: material.difficulty,
        totalRecords,
        averageScore,
        completionRate
      };
    }));

    res.json(materialStats);
  } catch (error) {
    res.status(500).json({ message: '获取材料难度分析失败', error });
  }
}; 